document.addEventListener('DOMContentLoaded', function() {
    // 加载系统使用申请列表
    loadApplications();
    
    // 搜索按钮点击事件
    document.getElementById('search-btn').addEventListener('click', function() {
        loadApplications();
    });
    
    // 状态筛选器变更事件
    document.getElementById('status-filter').addEventListener('change', function() {
        loadApplications();
    });
    
    // 关键词搜索框回车事件
    document.getElementById('keyword-search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            loadApplications();
        }
    });
    
    // 详情模态框关闭按钮
    document.querySelector('#details-modal .modal-close').addEventListener('click', function() {
        closeDetailsModal();
    });
    
    // 详情模态框关闭按钮
    document.getElementById('details-close').addEventListener('click', function() {
        closeDetailsModal();
    });
    
    // 公司搜索按钮点击事件
    document.getElementById('company-search-btn').addEventListener('click', function() {
        loadCompanies();
    });
    
    // 公司关键词搜索框回车事件
    document.getElementById('company-keyword').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            loadCompanies();
        }
    });
    
    // 公司搜索类型变更事件
    document.getElementById('company-search-type').addEventListener('change', function() {
        const keyword = document.getElementById('company-keyword');
        const searchType = this.value;
        
        if (searchType === 'all') {
            keyword.placeholder = '默认显示所有公司';
            keyword.disabled = true;
        } else {
            keyword.disabled = false;
            switch (searchType) {
                case 'id':
                    keyword.placeholder = '请输入公司ID';
                    break;
                case 'manager':
                    keyword.placeholder = '请输入负责人姓名';
                    break;
                case 'creditCode':
                    keyword.placeholder = '请输入统一社会信用代码';
                    break;
                default:
                    keyword.placeholder = '请输入搜索关键词';
            }
        }
    });
    
    // 公司详情模态框关闭按钮
    document.querySelector('#company-details-modal .modal-close').addEventListener('click', function() {
        closeCompanyDetailsModal();
    });
    
    // 公司详情模态框关闭按钮
    document.getElementById('company-details-close').addEventListener('click', function() {
        closeCompanyDetailsModal();
    });
    
    // 公司状态按钮点击事件
    document.getElementById('company-status-btn').addEventListener('click', function() {
        updateCompanyStatus();
    });
    
    // 用户搜索按钮点击事件
    document.getElementById('user-search-btn').addEventListener('click', function() {
        loadUsers();
    });
    
    // 用户关键词搜索框回车事件
    document.getElementById('user-keyword').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            loadUsers();
        }
    });
    
    // 用户详情模态框关闭按钮
    document.querySelector('#user-details-modal .modal-close').addEventListener('click', function() {
        closeUserDetailsModal();
    });
    
    // 用户详情模态框关闭按钮
    document.getElementById('user-details-close').addEventListener('click', function() {
        closeUserDetailsModal();
    });
    
    // 菜单项点击事件
    document.querySelectorAll('.submenu a').forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有菜单项的active类
            document.querySelectorAll('.submenu a').forEach(function(item) {
                item.classList.remove('active');
            });
            
            // 添加当前菜单项的active类
            this.classList.add('active');
            
            // 隐藏所有内容区域
            document.querySelectorAll('.function-content').forEach(function(content) {
                content.classList.remove('active');
            });
            
            // 显示对应的内容区域
            const targetId = this.getAttribute('data-target');
            document.getElementById(targetId).classList.add('active');
            
            // 根据菜单项加载不同的数据
            if (targetId === 'system-applications') {
                loadApplications();
            } else if (targetId === 'find-company') {
                loadCompanies();
            } else if (targetId === 'find-user') {
                loadUsers();
            }
        });
    });
    
    // 刷新按钮点击事件
    document.getElementById('refresh-btn').addEventListener('click', function() {
        // 获取当前活动的内容区域
        const activeContent = document.querySelector('.function-content.active');
        if (activeContent) {
            const contentId = activeContent.id;
            
            if (contentId === 'system-applications') {
                loadApplications();
            } else if (contentId === 'find-company') {
                loadCompanies();
            } else if (contentId === 'find-user') {
                loadUsers();
            }
        }
    });
});

// 全局变量
let applications = []; // 存储当前显示的申请列表
let companies = []; // 存储当前显示的公司列表
let users = []; // 存储当前显示的用户列表
let currentCompany = null; // 当前查看的公司详情
let currentUser = null; // 当前查看的用户详情
let currentPage = 1; // 当前页码
let currentCompanyPage = 1; // 当前公司页码
let currentUserPage = 1; // 当前用户页码
const itemsPerPage = 8; // 每页显示数量

// 加载系统使用申请列表
function loadApplications() {
    const statusFilter = document.getElementById('status-filter').value;
    const keyword = document.getElementById('keyword-search').value.trim();
    
    // 构建查询参数
    let url = 'getApplications';
    let params = [];
    
    if (statusFilter) {
        params.push('status=' + statusFilter);
    }
    
    if (keyword) {
        params.push('keyword=' + encodeURIComponent(keyword));
    }
    
    if (params.length > 0) {
        url += '?' + params.join('&');
    }
    
    // 显示加载中提示
    document.getElementById('applications-list').innerHTML = '<p class="text-center">加载中，请稍候...</p>';
    
    // 发起请求
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            applications = data.applications || [];
            currentPage = 1;
            renderApplications();
        } else {
            document.getElementById('applications-list').innerHTML = 
                `<div class="empty-result">
                    <p>加载失败: ${data.message}</p>
                </div>`;
        }
    })
    .catch(error => {
        console.error('加载申请列表出错:', error);
        document.getElementById('applications-list').innerHTML = 
            `<div class="empty-result">
                <p>加载出错，请稍后重试</p>
            </div>`;
    });
}

// 加载公司列表
function loadCompanies() {
    const searchType = document.getElementById('company-search-type').value;
    const keyword = document.getElementById('company-keyword').value.trim();
    
    // 构建查询参数
    let url = 'admin/searchCompany';
    let params = [];
    
    if (searchType && searchType !== 'all') {
        params.push('searchType=' + searchType);
        if (keyword) {
            params.push('keyword=' + encodeURIComponent(keyword));
        }
    }
    
    if (params.length > 0) {
        url += '?' + params.join('&');
    }
    
    // 显示加载中提示
    document.getElementById('companies-list').innerHTML = '<p class="text-center">加载中，请稍候...</p>';
    
    // 发起请求
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            companies = data.companies || [];
            currentCompanyPage = 1;
            renderCompanies();
        } else {
            document.getElementById('companies-list').innerHTML = 
                `<div class="empty-result">
                    <p>加载失败: ${data.message}</p>
                </div>`;
        }
    })
    .catch(error => {
        console.error('加载公司列表出错:', error);
        document.getElementById('companies-list').innerHTML = 
            `<div class="empty-result">
                <p>加载出错，请稍后重试</p>
            </div>`;
    });
}

// 搜索公司
function searchCompanies() {
    const searchType = document.getElementById('company-search-type').value;
    const keyword = document.getElementById('company-keyword').value.trim();
    
    // 构建查询参数
    let url = 'admin/searchCompany';
    let params = [];
    
    if (searchType && searchType !== 'all') {
        params.push('searchType=' + searchType);
        if (keyword) {
            params.push('keyword=' + encodeURIComponent(keyword));
        }
    }
    
    if (params.length > 0) {
        url += '?' + params.join('&');
    }
    
    // 显示加载中提示
    document.getElementById('companies-list').innerHTML = '<p class="text-center">加载中，请稍候...</p>';
    
    // 发起请求
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            companies = data.companies || [];
            currentCompanyPage = 1;
            renderCompanies();
        } else {
            document.getElementById('companies-list').innerHTML = 
                `<div class="empty-result">
                    <p>加载失败: ${data.message}</p>
                </div>`;
        }
    })
    .catch(error => {
        console.error('加载公司列表出错:', error);
        document.getElementById('companies-list').innerHTML = 
            `<div class="empty-result">
                <p>加载出错，请稍后重试</p>
            </div>`;
    });
}

// 渲染公司列表
function renderCompanies() {
    const listContainer = document.getElementById('companies-list');
    
    if (companies.length === 0) {
        listContainer.innerHTML = 
            `<div class="empty-result">
                <p>没有找到符合条件的公司记录</p>
            </div>`;
        document.getElementById('company-pagination').innerHTML = '';
        return;
    }
    
    // 计算分页
    const totalPages = Math.ceil(companies.length / itemsPerPage);
    if (currentCompanyPage > totalPages) {
        currentCompanyPage = totalPages;
    }
    
    // 计算当前页的数据范围
    const startIndex = (currentCompanyPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, companies.length);
    const currentPageData = companies.slice(startIndex, endIndex);
    
    // 创建表格
    let tableHtml = `
        <table class="companies-table">
            <thead>
                <tr>
                    <th>公司ID</th>
                    <th>公司名称</th>
                    <th>负责人</th>
                    <th>联系电话</th>
                    <th>统一社会信用代码</th>
                    <th>员工数量</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充表格数据
    currentPageData.forEach(company => {
        const createDate = new Date(company.createTime);
        const formattedDate = createDate.toLocaleString('zh-CN');
        
        let statusBadge = '';
        switch (company.status) {
            case 0:
                statusBadge = '<span class="status-badge status-disabled">已禁用</span>';
                break;
            case 1:
                statusBadge = '<span class="status-badge status-active">正常</span>';
                break;
            case 2:
                statusBadge = '<span class="status-badge status-pending">待审核</span>';
                break;
            default:
                statusBadge = '<span class="status-badge">未知</span>';
        }
        
        tableHtml += `
            <tr onclick="viewCompanyDetails('${company.id}')">
                <td>${company.id}</td>
                <td>${company.name}</td>
                <td>${company.manager ? company.manager.name : '未知'}</td>
                <td>${company.phone}</td>
                <td>${company.creditCode}</td>
                <td>${company.employeeCount}</td>
                <td>${statusBadge}</td>
            </tr>
        `;
    });
    
    tableHtml += `
            </tbody>
        </table>
    `;
    
    listContainer.innerHTML = tableHtml;
    
    // 渲染分页控件
    renderCompanyPagination(totalPages);
}

// 渲染公司分页控件
function renderCompanyPagination(totalPages) {
    const paginationContainer = document.getElementById('company-pagination');
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHtml = '';
    
    // 上一页按钮
    paginationHtml += `
        <button ${currentCompanyPage === 1 ? 'disabled' : ''} onclick="changeCompanyPage(${currentCompanyPage - 1})">
            上一页
        </button>
    `;
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        paginationHtml += `
            <button class="${currentCompanyPage === i ? 'active' : ''}" onclick="changeCompanyPage(${i})">
                ${i}
            </button>
        `;
    }
    
    // 下一页按钮
    paginationHtml += `
        <button ${currentCompanyPage === totalPages ? 'disabled' : ''} onclick="changeCompanyPage(${currentCompanyPage + 1})">
            下一页
        </button>
    `;
    
    paginationContainer.innerHTML = paginationHtml;
}

// 切换公司页码
function changeCompanyPage(page) {
    currentCompanyPage = page;
    renderCompanies();
    // 滚动到列表顶部
    document.getElementById('companies-list').scrollIntoView({ behavior: 'smooth' });
}

// 查看公司详情
function viewCompanyDetails(companyId) {
    // 显示加载中提示
    document.getElementById('company-details-modal').style.display = 'block';
    document.getElementById('company-basic-details').innerHTML = '<p>加载中，请稍候...</p>';
    document.getElementById('company-manager-details').innerHTML = '';
    document.getElementById('company-employee-summary').innerHTML = '';
    document.getElementById('company-status-btn').style.display = 'none';
    
    // 发起请求获取公司详情
    console.log('正在获取公司详情: companyId=' + companyId);
    
    fetch(`admin/getCompanyDetail?companyId=${companyId}`)
    .then(response => {
        console.log('获取公司详情响应状态: ' + response.status);
        return response.json(); // 直接解析为JSON
    })
    .then(data => {
        console.log('解析后的数据: ', data);
        if (data.success) {
            currentCompany = data.company;
            displayCompanyDetails(currentCompany);
        } else {
            document.getElementById('company-basic-details').innerHTML = '<p class="error-message">获取公司详情失败: ' + data.message + '</p>';
            document.getElementById('company-status-btn').style.display = 'none';
        }
    })
    .catch(error => {
        console.error('获取公司详情出错:', error);
        document.getElementById('company-basic-details').innerHTML = '<p class="error-message">获取公司详情出错，请稍后重试</p>';
        document.getElementById('company-status-btn').style.display = 'none';
    });
}

// 显示公司详情
function displayCompanyDetails(company) {
    try {
        console.log('显示公司详情: ', company);
        
        // 确保company对象存在
        if (!company) {
            document.getElementById('company-basic-details').innerHTML = '<p class="error-message">无法获取公司详情</p>';
            document.getElementById('company-status-btn').style.display = 'none';
            return;
        }
        
        // 填充基本信息
        const basicDetailsContainer = document.getElementById('company-basic-details');
        
        let statusText = '';
        switch (company.status) {
            case 0:
                statusText = '<span class="status-badge status-disabled">已禁用</span>';
                break;
            case 1:
                statusText = '<span class="status-badge status-active">正常</span>';
                break;
            case 2:
                statusText = '<span class="status-badge status-pending">待审核</span>';
                break;
            default:
                statusText = '<span class="status-badge">未知</span>';
        }
        
        basicDetailsContainer.innerHTML = `
            <dt>公司ID</dt>
            <dd>${company.id}</dd>
            <dt>公司名称</dt>
            <dd>${company.name}</dd>
            <dt>公司地址</dt>
            <dd>${company.address || '未设置'}</dd>
            <dt>联系电话</dt>
            <dd>${company.phone || '未设置'}</dd>
            <dt>统一社会信用代码</dt>
            <dd>${company.creditCode}</dd>
            <dt>员工数量</dt>
            <dd>${company.employeeCount}</dd>
            <dt>创建时间</dt>
            <dd>${new Date(company.createTime).toLocaleString('zh-CN')}</dd>
            <dt>状态</dt>
            <dd>${statusText}</dd>
        `;
        
        // 填充负责人信息
        const managerDetailsContainer = document.getElementById('company-manager-details');
        if (company.manager) {
            managerDetailsContainer.innerHTML = `
                <dt>负责人ID</dt>
                <dd>${company.manager.id}</dd>
                <dt>负责人姓名</dt>
                <dd>${company.manager.name}</dd>
                <dt>联系电话</dt>
                <dd>${company.manager.phone || '未设置'}</dd>
                <dt>电子邮箱</dt>
                <dd>${company.manager.email || '未设置'}</dd>
                <dt>性别</dt>
                <dd>${company.manager.gender || '未设置'}</dd>
                <dt>年龄</dt>
                <dd>${company.manager.age || '未设置'}</dd>
            `;
        } else {
            managerDetailsContainer.innerHTML = '<p>无法获取负责人信息</p>';
        }
        
        // 填充员工信息摘要
        const employeeSummaryContainer = document.getElementById('company-employee-summary');
        if (company.employeeSummary) {
            let departmentHtml = '';
            if (company.employeeSummary.departmentCount) {
                for (const [department, count] of Object.entries(company.employeeSummary.departmentCount)) {
                    departmentHtml += `
                        <div class="department-stat">
                            <strong>${department || '未分配部门'}</strong>: ${count}人
                        </div>
                    `;
                }
            }
            
            employeeSummaryContainer.innerHTML = '<p>暂无员工信息</p>';
            if (company.employeeSummary.total > 0) {
                employeeSummaryContainer.innerHTML = `
                    <p>当前在职员工总数: <strong>${company.employeeSummary.total || 0}</strong> 人</p>
                `;
            }
        } else {
            employeeSummaryContainer.innerHTML = '<p>暂无员工信息</p>';
        }
        
        // 设置状态按钮文本
        const statusBtn = document.getElementById('company-status-btn');
        statusBtn.style.display = 'inline-block';
        
        if (company.status === 1) {
            statusBtn.textContent = '禁用公司';
            statusBtn.classList.add('danger');
            statusBtn.classList.remove('approve-btn');
        } else if (company.status === 0) {
            statusBtn.textContent = '恢复公司';
            statusBtn.classList.remove('danger');
            statusBtn.classList.add('approve-btn');
        } else if (company.status === 2) {
            statusBtn.textContent = '恢复公司';
            statusBtn.classList.remove('danger');
            statusBtn.classList.add('approve-btn');
        }
        
        // 添加删除公司按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.textContent = '注销公司';
        deleteBtn.className = 'btn btn-danger delete-company-btn';
        deleteBtn.style.marginRight = '10px';
        deleteBtn.onclick = function() {
            confirmDeleteCompany(company.id, company.name);
        };
        
        // 将删除按钮添加到模态框底部
        const modalFooter = document.querySelector('#company-details-modal .modal-footer');
        if (modalFooter) {
            // 先移除可能存在的旧按钮
            const oldDeleteBtn = modalFooter.querySelector('.delete-company-btn');
            if (oldDeleteBtn) {
                modalFooter.removeChild(oldDeleteBtn);
            }
            
            // 添加新按钮到状态按钮之前
            modalFooter.insertBefore(deleteBtn, statusBtn);
        }
    } catch (error) {
        console.error('显示公司详情出错:', error);
        document.getElementById('company-basic-details').innerHTML = '<p class="error-message">显示公司详情出错: ' + error.message + '</p>';
        document.getElementById('company-status-btn').style.display = 'none';
    }
}

// 关闭公司详情模态框
function closeCompanyDetailsModal() {
    document.getElementById('company-details-modal').style.display = 'none';
    currentCompany = null;
}

// 确认删除公司
function confirmDeleteCompany(companyId, companyName) {
    if (confirm(`确定要注销公司"${companyName}"吗？此操作将删除该公司的所有数据，包括员工关联、公告、打卡记录等，且不可恢复！`)) {
        if (confirm('再次确认：注销公司将删除公司负责人账号和所有相关数据，是否继续？')) {
            deleteCompany(companyId);
        }
    }
}

// 删除公司
function deleteCompany(companyId) {
    fetch('admin/deleteCompany', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `companyId=${companyId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', data.message, 'success');
            closeCompanyDetailsModal();
            loadCompanies(); // 重新加载公司列表
        } else {
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('删除公司出错:', error);
        showToast('错误', '删除公司失败，请稍后重试', 'error');
    });
}

// 更新公司状态（禁用/恢复）
function updateCompanyStatus() {
    if (!currentCompany) {
        alert('未选择公司');
        return;
    }
    
    const companyId = currentCompany.id;
    // 如果当前状态是1（正常），则设为0（禁用）；如果是0（禁用）或2（待审核），则设为1（正常）
    const newStatus = currentCompany.status === 1 ? 0 : 1;
    
    console.log('更新公司状态: companyId=' + companyId + ', newStatus=' + newStatus);
    
    // 显示确认对话框
    const confirmMessage = newStatus === 0 ? 
        '确定要禁用该公司吗？禁用后该公司的所有员工将无法登录系统。' : 
        '确定要恢复该公司的使用权限吗？';
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    // 禁用按钮，防止重复提交
    const statusBtn = document.getElementById('company-status-btn');
    statusBtn.disabled = true;
    statusBtn.textContent = '处理中...';
    
    // 使用URLSearchParams构建表单数据
    const formData = new URLSearchParams();
    formData.append('companyId', companyId);
    formData.append('status', newStatus.toString());
    
    console.log('发送的表单数据: companyId=' + companyId + ', status=' + newStatus.toString());
    
    fetch('admin/updateCompanyStatus', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData.toString()
    })
    .then(response => {
        console.log('响应状态码:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('更新公司状态响应:', data);
        
        if (data.success) {
            // 使用与确认对话框相同样式的弹窗显示成功消息
            alert(data.message);
            
            // 更新当前公司状态
            currentCompany.status = newStatus;
            
            // 更新详情显示
            displayCompanyDetails(currentCompany);
            
            // 刷新公司列表
            searchCompanies();
        } else {
            // 使用与确认对话框相同样式的弹窗显示错误消息
            alert(data.message || '操作失败');
        }
    })
    .catch(error => {
        console.error('更新公司状态出错:', error);
        alert('更新公司状态出错，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        statusBtn.disabled = false;
        statusBtn.textContent = currentCompany.status === 1 ? '禁用公司' : '恢复公司';
    });
}

// 渲染申请列表
function renderApplications() {
    const listContainer = document.getElementById('applications-list');
    
    if (applications.length === 0) {
        listContainer.innerHTML = 
            `<div class="empty-result">
                <p>没有找到符合条件的申请记录</p>
            </div>`;
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    
    // 计算分页
    const totalPages = Math.ceil(applications.length / itemsPerPage);
    if (currentPage > totalPages) {
        currentPage = totalPages;
    }
    
    // 计算当前页的数据范围
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, applications.length);
    const currentPageData = applications.slice(startIndex, endIndex);
    
    // 创建表格
    let tableHtml = `
        <table class="applications-table">
            <thead>
                <tr>
                    <th>申请ID</th>
                    <th>公司名称</th>
                    <th>负责人</th>
                    <th>联系电话</th>
                    <th>申请时间</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充表格数据
    currentPageData.forEach(app => {
        const createDate = new Date(app.createTime);
        const formattedDate = createDate.toLocaleString('zh-CN');
        
        let statusBadge = '';
        switch (app.status) {
            case 0:
                statusBadge = '<span class="status-badge status-pending">待审核</span>';
                break;
            case 1:
                statusBadge = '<span class="status-badge status-approved">已通过</span>';
                break;
            case 2:
                statusBadge = '<span class="status-badge status-rejected">已拒绝</span>';
                break;
            default:
                statusBadge = '<span class="status-badge">未知</span>';
        }
        
        let actionButtons = `
            <div class="action-buttons">
        `;
        
        // 只有待审核状态才显示审核按钮，按钮顺序：通过、拒绝、查看
        if (app.status === 0) {
            actionButtons += `
                <button class="approve-btn" onclick="directApprove('${app.id}')">通过</button>
                <button class="reject-btn" onclick="directReject('${app.id}')">拒绝</button>
            `;
        }
        
        // 查看按钮始终显示，但放在最后
        actionButtons += `<button class="view-btn" onclick="viewApplicationDetails('${app.id}')">查看</button>`;
        
        actionButtons += `</div>`;
        
        tableHtml += `
            <tr>
                <td>${app.id}</td>
                <td>${app.companyName}</td>
                <td>${app.userName}</td>
                <td>${app.userPhone}</td>
                <td>${formattedDate}</td>
                <td>${statusBadge}</td>
                <td>${actionButtons}</td>
            </tr>
        `;
    });
    
    tableHtml += `
            </tbody>
        </table>
    `;
    
    listContainer.innerHTML = tableHtml;
    
    // 渲染分页控件
    renderPagination(totalPages);
}

// 渲染分页控件
function renderPagination(totalPages) {
    const paginationContainer = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHtml = '';
    
    // 上一页按钮
    paginationHtml += `
        <button ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">
            上一页
        </button>
    `;
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        paginationHtml += `
            <button class="${currentPage === i ? 'active' : ''}" onclick="changePage(${i})">
                ${i}
            </button>
        `;
    }
    
    // 下一页按钮
    paginationHtml += `
        <button ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">
            下一页
        </button>
    `;
    
    paginationContainer.innerHTML = paginationHtml;
}

// 切换页码
function changePage(page) {
    currentPage = page;
    renderApplications();
    // 滚动到列表顶部
    document.getElementById('applications-list').scrollIntoView({ behavior: 'smooth' });
}

// 显示申请详情
function viewApplicationDetails(applicationId) {
    const application = applications.find(app => app.id === applicationId);
    
    if (!application) {
        alert('找不到申请详情');
        return;
    }
    
    const createDate = new Date(application.createTime);
    const formattedCreateDate = createDate.toLocaleString('zh-CN');
    
    const updateDate = new Date(application.updateTime);
    const formattedUpdateDate = updateDate.toLocaleString('zh-CN');
    
    let statusText = '';
    switch (application.status) {
        case 0:
            statusText = '待审核';
            break;
        case 1:
            statusText = '已通过';
            break;
        case 2:
            statusText = '已拒绝';
            break;
        default:
            statusText = '未知';
    }
    
    const detailsContainer = document.getElementById('application-details');
    detailsContainer.innerHTML = `
        <dt>申请ID</dt>
        <dd>${application.id}</dd>
        
        <dt>申请人</dt>
        <dd>${application.userName}</dd>
        
        <dt>联系电话</dt>
        <dd>${application.userPhone}</dd>
        
        <dt>公司名称</dt>
        <dd>${application.companyName}</dd>
        
        <dt>统一社会信用代码</dt>
        <dd>${application.companyCreditCode}</dd>
        
        <dt>申请理由</dt>
        <dd>${application.reason || '未提供'}</dd>
        
        <dt>申请时间</dt>
        <dd>${formattedCreateDate}</dd>
        
        <dt>更新时间</dt>
        <dd>${formattedUpdateDate}</dd>
        
        <dt>状态</dt>
        <dd>${statusText}</dd>
    `;
    
    // 如果已拒绝，显示拒绝原因
    if (application.status === 2 && application.rejectReason) {
        detailsContainer.innerHTML += `
            <dt>拒绝原因</dt>
            <dd>${application.rejectReason}</dd>
        `;
    }
    
    // 显示模态框
    document.getElementById('details-modal').style.display = 'block';
}

// 关闭详情模态框
function closeDetailsModal() {
    document.getElementById('details-modal').style.display = 'none';
}

// 直接通过申请
function directApprove(applicationId) {
    console.log("准备通过申请:", applicationId);
    if (confirm('确定要通过该申请吗？申请ID: ' + applicationId)) {
        submitReviewDirect(applicationId, 1, '通过');
    }
}

// 直接拒绝申请
function directReject(applicationId) {
    const reason = prompt('请输入拒绝原因:');
    if (reason !== null) {
        submitReviewDirect(applicationId, 2, reason);
    }
}

// 提交审核结果
function submitReviewDirect(applicationId, status, reason) {
    // 打印参数，用于调试
    console.log("提交审核参数:", { applicationId, status, reason });
    
    // 使用XMLHttpRequest
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'reviewApplication', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    
    // 构建请求参数
    const rejectReason = reason || (status === 1 ? "通过" : "拒绝");
    const params = `applicationId=${encodeURIComponent(applicationId)}&status=${encodeURIComponent(status)}&rejectReason=${encodeURIComponent(rejectReason)}`;
    
    console.log("发送请求参数:", params);
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    const data = JSON.parse(xhr.responseText);
                    console.log("服务器响应:", data);
                    
                    if (data.success) {
                        alert(data.message);
                        loadApplications(); // 重新加载申请列表
                    } else {
                        alert('审核失败: ' + data.message);
                        console.error('审核失败详情:', data);
                    }
                } catch (e) {
                    console.error('解析响应失败:', e);
                    alert('审核出错，服务器响应无效');
                }
            } else {
                console.error('请求失败:', xhr.status);
                alert('审核出错，请求失败');
            }
        }
    };
    
    xhr.send(params);
}

// 显示操作结果提示
function showToast(title, message, type) {
    // 使用浏览器自带的alert
    alert(title + ': ' + message);
}

// 加载用户列表
function loadUsers() {
    const searchType = document.getElementById('user-search-type').value;
    const keyword = document.getElementById('user-keyword').value.trim();
    
    // 构建查询参数
    let url = 'admin/searchUser';
    let params = [];
    
    if (searchType) {
        params.push('searchType=' + searchType);
    }
    
    if (keyword) {
        params.push('keyword=' + encodeURIComponent(keyword));
    }
    
    if (params.length > 0) {
        url += '?' + params.join('&');
    }
    
    // 显示加载中提示
    document.getElementById('users-list').innerHTML = '<p class="text-center">加载中，请稍候...</p>';
    
    // 发起请求
    fetch(url)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            users = data.users || [];
            currentUserPage = 1;
            renderUsers();
        } else {
            document.getElementById('users-list').innerHTML = 
                `<div class="empty-result">
                    <p>加载失败: ${data.message}</p>
                </div>`;
        }
    })
    .catch(error => {
        console.error('加载用户列表出错:', error);
        document.getElementById('users-list').innerHTML = 
            `<div class="empty-result">
                <p>加载出错，请稍后重试</p>
            </div>`;
    });
}

// 渲染用户列表
function renderUsers() {
    const listContainer = document.getElementById('users-list');
    
    // 如果没有数据
    if (!users || users.length === 0) {
        listContainer.innerHTML = 
            `<div class="empty-result">
                <p>没有找到匹配的用户</p>
            </div>`;
        document.getElementById('users-pagination').innerHTML = '';
        return;
    }
    
    // 计算分页
    const totalPages = Math.ceil(users.length / itemsPerPage);
    if (currentUserPage > totalPages) {
        currentUserPage = totalPages;
    }
    
    // 获取当前页的数据
    const startIndex = (currentUserPage - 1) * itemsPerPage;
    const endIndex = Math.min(startIndex + itemsPerPage, users.length);
    const currentPageData = users.slice(startIndex, endIndex);
    
    // 构建表格HTML
    let tableHtml = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>手机号</th>
                    <th>角色</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 填充表格数据
    currentPageData.forEach(user => {
        let roleName;
        switch (user.role) {
            case 0:
                roleName = '普通用户';
                break;
            case 1:
                roleName = '公司负责人';
                break;
            case 2:
                roleName = '系统管理员';
                break;
            default:
                roleName = '未知角色';
        }
        
        let statusBadge;
        if (user.status === 0) {
            statusBadge = '<span class="status-badge status-rejected">已禁用</span>';
        } else {
            statusBadge = '<span class="status-badge status-approved">正常</span>';
        }
        
        tableHtml += `
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.phone}</td>
                <td>${roleName}</td>
                <td>${statusBadge}</td>
                <td>
                    <div class="action-buttons">
                        <button class="view-btn" onclick="viewUserDetails('${user.id}')">查看</button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    tableHtml += `
            </tbody>
        </table>
    `;
    
    listContainer.innerHTML = tableHtml;
    
    // 渲染分页控件
    renderUserPagination(totalPages);
}

// 渲染用户分页控件
function renderUserPagination(totalPages) {
    const paginationContainer = document.getElementById('users-pagination');
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHtml = '<div class="pagination-controls">';
    
    // 上一页按钮
    if (currentUserPage > 1) {
        paginationHtml += `<button onclick="changeUserPage(${currentUserPage - 1})">上一页</button>`;
    } else {
        paginationHtml += `<button disabled>上一页</button>`;
    }
    
    // 页码按钮
    const maxPagesToShow = 5;
    let startPage = Math.max(1, currentUserPage - Math.floor(maxPagesToShow / 2));
    let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
    
    if (endPage - startPage + 1 < maxPagesToShow) {
        startPage = Math.max(1, endPage - maxPagesToShow + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        if (i === currentUserPage) {
            paginationHtml += `<button class="active">${i}</button>`;
        } else {
            paginationHtml += `<button onclick="changeUserPage(${i})">${i}</button>`;
        }
    }
    
    // 下一页按钮
    if (currentUserPage < totalPages) {
        paginationHtml += `<button onclick="changeUserPage(${currentUserPage + 1})">下一页</button>`;
    } else {
        paginationHtml += `<button disabled>下一页</button>`;
    }
    
    paginationHtml += '</div>';
    paginationContainer.innerHTML = paginationHtml;
}

// 切换用户页面
function changeUserPage(page) {
    currentUserPage = page;
    renderUsers();
    
    // 滚动到列表顶部
    document.getElementById('users-list').scrollIntoView({ behavior: 'smooth' });
}

// 查看用户详情
function viewUserDetails(userId) {
    // 清理之前的提示信息
    const modalBody = document.querySelector('#user-details-modal .modal-body');
    const existingNote = modalBody.querySelector('.note-message');
    if (existingNote) {
        existingNote.remove();
    }
    
    // 查找用户
    const user = users.find(u => u.id === userId);
    if (!user) {
        showToast('错误', '未找到用户信息', 'error');
        return;
    }
    
    // 保存当前用户
    currentUser = user;
    
    // 填充用户详情
    const detailsContainer = document.getElementById('user-details');
    
    let roleName;
    switch (user.role) {
        case 0:
            roleName = '普通用户';
            break;
        case 1:
            roleName = '公司负责人';
            break;
        case 2:
            roleName = '系统管理员';
            break;
        default:
            roleName = '未知角色';
    }
    
    let statusText = user.status === 0 ? '已禁用' : '正常';
    
    let detailsHtml = `
        <dt>用户ID</dt>
        <dd>${user.id}</dd>
        
        <dt>姓名</dt>
        <dd>${user.name}</dd>
        
        <dt>性别</dt>
        <dd>${user.gender || '未设置'}</dd>
        
        <dt>年龄</dt>
        <dd>${user.age || '未设置'}</dd>
        
        <dt>手机号</dt>
        <dd>${user.phone}</dd>
        
        <dt>邮箱</dt>
        <dd>${user.email || '未设置'}</dd>
        
        <dt>住址</dt>
        <dd>${user.address || '未设置'}</dd>
        
        <dt>身份证号</dt>
        <dd>${user.idCard || '未设置'}</dd>
        
        <dt>角色</dt>
        <dd>${roleName}</dd>
        
        <dt>状态</dt>
        <dd>${statusText}</dd>
    `;
    
    // 如果是公司负责人，显示公司信息
    if (user.role === 1) {
        detailsHtml += `
            <dt>公司名称</dt>
            <dd>${user.companyName || '未设置'}</dd>
            
            <dt>公司地址</dt>
            <dd>${user.companyAddress || '未设置'}</dd>
            
            <dt>公司电话</dt>
            <dd>${user.companyPhone || '未设置'}</dd>
            
            <dt>统一社会信用代码</dt>
            <dd>${user.companyCreditCode || '未设置'}</dd>
        `;
    }
    
    // 如果是普通用户且有公司ID，显示所属公司信息
    if (user.role === 0 && user.companyId) {
        detailsHtml += `
            <dt>所属公司ID</dt>
            <dd>${user.companyId}</dd>
            
            <dt>员工编号</dt>
            <dd>${user.employeeNumber || '未设置'}</dd>
        `;
    }
    
    detailsContainer.innerHTML = detailsHtml;
    
    // 设置状态按钮文本
    const statusBtn = document.getElementById('user-status-btn');
    if (user.status === 0) {
        statusBtn.textContent = '恢复用户';
        statusBtn.classList.remove('danger');
        statusBtn.classList.add('primary');
    } else {
        statusBtn.textContent = '禁用用户';
        statusBtn.classList.remove('primary');
        statusBtn.classList.add('danger');
    }
    
    // 绑定状态按钮点击事件
    statusBtn.onclick = function() {
        updateUserStatus(user.id, user.status === 0 ? 1 : 0);
    };
    
    // 绑定注销用户按钮点击事件
    const deleteBtn = document.getElementById('user-delete-btn');
    // 系统管理员和公司负责人不能被注销
    if (user.role === 2 || user.role === 1) {
        deleteBtn.style.display = 'none';
        
        // 如果是公司负责人，添加提示信息
        if (user.role === 1) {
            const modalBody = document.querySelector('#user-details-modal .modal-body');
            const noteElement = document.createElement('div');
            noteElement.className = 'note-message';
            noteElement.innerHTML = '<p><strong>注意：</strong>公司负责人用户需要通过公司注销功能来完成注销流程</p>';
            modalBody.appendChild(noteElement);
        }
    } else {
        deleteBtn.style.display = 'inline-block';
        deleteBtn.onclick = function() {
            confirmDeleteUser(user.id, user.name);
        };
    }
    
    // 显示模态框
    document.getElementById('user-details-modal').style.display = 'block';
}

// 确认注销用户
function confirmDeleteUser(userId, userName) {
    if (confirm(`确定要注销用户"${userName}"吗？\n注销后该用户将退出所有公司并删除账号，此操作不可恢复！`)) {
        deleteUser(userId);
    }
}

// 注销用户
function deleteUser(userId) {
    // 发起请求
    fetch('api/admin/deleteUser', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `userId=${userId}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新成功，关闭模态框
            closeUserDetailsModal();
            
            // 刷新用户列表
            loadUsers();
            
            // 显示成功提示
            showToast('成功', data.message, 'success');
        } else {
            // 显示错误提示
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('注销用户出错:', error);
        showToast('错误', '服务器错误，请稍后重试', 'error');
    });
}

// 关闭用户详情模态框
function closeUserDetailsModal() {
    document.getElementById('user-details-modal').style.display = 'none';
    currentUser = null;
}

// 更新用户状态
function updateUserStatus(userId, status) {
    // 发起请求
    fetch('admin/updateUserStatus', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `userId=${userId}&status=${status}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新成功，关闭模态框
            closeUserDetailsModal();
            
            // 刷新用户列表
            loadUsers();
            
            // 显示成功提示
            showToast('成功', data.message, 'success');
        } else {
            // 显示错误提示
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新用户状态出错:', error);
        showToast('错误', '服务器错误，请稍后重试', 'error');
    });
} 

// 修改密码表单提交事件
document.addEventListener('DOMContentLoaded', function() {
    const changePasswordForm = document.getElementById('change-password-form');
    if (changePasswordForm) {
        changePasswordForm.addEventListener('submit', function(e) {
            e.preventDefault();
            updateAdminPassword();
        });
    }
    
    // 新密码输入验证
    const newPasswordInput = document.getElementById('new-password');
    if (newPasswordInput) {
        newPasswordInput.addEventListener('input', validateNewPassword);
    }
    
    // 确认密码输入验证
    const confirmPasswordInput = document.getElementById('confirm-password');
    if (confirmPasswordInput) {
        confirmPasswordInput.addEventListener('input', validateConfirmPassword);
    }
});

// 验证新密码
function validateNewPassword() {
    const newPassword = document.getElementById('new-password').value;
    const requirements = document.getElementById('new-password').nextElementSibling;
    
    // 检查密码长度
    const lengthValid = newPassword.length >= 6;
    
    // 更新提示信息
    const requirementsList = requirements.querySelector('ul');
    if (requirementsList) {
        const items = requirementsList.querySelectorAll('li');
        items[0].style.color = lengthValid ? 'green' : 'red';
    }
    
    return lengthValid;
}

// 验证确认密码
function validateConfirmPassword() {
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const requirements = document.getElementById('confirm-password').nextElementSibling;
    
    const isMatch = newPassword === confirmPassword;
    
    // 显示匹配状态
    if (confirmPassword) {
        if (!requirements.querySelector('p')) {
            const matchStatus = document.createElement('p');
            requirements.appendChild(matchStatus);
        }
        
        const matchStatus = requirements.querySelector('p');
        if (isMatch) {
            matchStatus.textContent = '密码匹配';
            matchStatus.style.color = 'green';
        } else {
            matchStatus.textContent = '密码不匹配';
            matchStatus.style.color = 'red';
        }
    } else {
        requirements.innerHTML = '';
    }
    
    return isMatch;
}

// 更新管理员密码
function updateAdminPassword() {
    const oldPassword = document.getElementById('old-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    // 验证输入
    if (!oldPassword) {
        showToast('错误', '请输入当前密码', 'error');
        return;
    }
    
    if (!validateNewPassword()) {
        showToast('错误', '新密码不符合要求', 'error');
        return;
    }
    
    if (!validateConfirmPassword()) {
        showToast('错误', '两次输入的密码不一致', 'error');
        return;
    }
    
    // 发送更新密码请求
    fetch('updateAdminPassword', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            oldPassword: oldPassword,
            newPassword: newPassword,
            confirmPassword: confirmPassword
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', data.message, 'success');
            
            // 清空表单
            document.getElementById('old-password').value = '';
            document.getElementById('new-password').value = '';
            document.getElementById('confirm-password').value = '';
            
            // 清除密码验证提示
            document.getElementById('confirm-password').nextElementSibling.innerHTML = '';
            
            // 重置新密码要求颜色
            const requirementsList = document.getElementById('new-password').nextElementSibling.querySelector('ul');
            if (requirementsList) {
                const items = requirementsList.querySelectorAll('li');
                items.forEach(item => {
                    item.style.color = '#666';
                });
            }
        } else {
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新密码出错:', error);
        showToast('错误', '更新密码失败，请稍后重试', 'error');
    });
}

// AI设置相关功能
// 页面加载完成后绑定AI设置事件
document.addEventListener('DOMContentLoaded', function() {
    // 绑定AI设置相关事件监听器
    bindAISettingsEvents();
});

function bindAISettingsEvents() {
    // 模型管理事件
    const addModelBtn = document.getElementById('add-model-btn');
    if (addModelBtn) {
        addModelBtn.addEventListener('click', showAddModelDialog);
    }

    const refreshModelsBtn = document.getElementById('refresh-models-btn');
    if (refreshModelsBtn) {
        refreshModelsBtn.addEventListener('click', loadAIModels);
    }

    // 限制设置事件
    const updateLimitBtn = document.getElementById('update-default-limit-btn');
    if (updateLimitBtn) {
        updateLimitBtn.addEventListener('click', updateDefaultLimit);
    }

    const searchUserBtn = document.getElementById('search-user-btn');
    if (searchUserBtn) {
        searchUserBtn.addEventListener('click', searchUserForAI);
    }

    // 系统设置事件
    const updateEnabledBtn = document.getElementById('update-ai-enabled-btn');
    if (updateEnabledBtn) {
        updateEnabledBtn.addEventListener('click', updateAIEnabled);
    }

    const updateModelBtn = document.getElementById('update-default-model-btn');
    if (updateModelBtn) {
        updateModelBtn.addEventListener('click', updateDefaultModel);
    }

    // 监听二级菜单切换，当切换到AI设置时加载数据
    const aiSettingsLink = document.querySelector('a[data-target="ai-settings"]');
    if (aiSettingsLink) {
        aiSettingsLink.addEventListener('click', function() {
            loadAISettings();
        });
    }
}

// 加载AI设置
function loadAISettings() {
    Promise.all([
        loadAIModels(),
        loadAISystemSettings()
    ]).catch(error => {
        console.error('加载AI设置失败:', error);
    });
}

// 加载AI模型列表
function loadAIModels() {
    return fetch('/xuanzheng-company/aiModels')
        .then(response => response.json())
        .then(data => {
            renderAIModels(data);
            updateModelSelect(data);
        })
        .catch(error => {
            console.error('加载AI模型失败:', error);
            const container = document.getElementById('ai-models-list');
            if (container) {
                container.innerHTML = '<p class="error-message">加载AI模型失败</p>';
            }
        });
}

// 渲染AI模型列表
function renderAIModels(models) {
    const container = document.getElementById('ai-models-list');
    if (!container) return;

    if (!models || models.length === 0) {
        container.innerHTML = '<p class="text-muted">暂无AI模型</p>';
        return;
    }

    container.innerHTML = models.map(model => `
        <div class="model-item">
            <div class="model-info">
                <h4>${model.name}</h4>
                <p>${model.description || '暂无描述'}</p>
                <small>API地址: ${model.apiUrl}</small>
            </div>
            <div class="model-actions">
                <span class="model-status ${model.status === 1 ? 'active' : 'inactive'}">
                    ${model.status === 1 ? '启用' : '禁用'}
                </span>
                <button class="btn btn-sm btn-primary" onclick="editAIModel('${model.id}')">编辑</button>
                <button class="btn btn-sm ${model.status === 1 ? 'btn-warning' : 'btn-success'}" 
                        onclick="toggleAIModel('${model.id}', ${model.status})">
                    ${model.status === 1 ? '禁用' : '启用'}
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteAIModel('${model.id}')">删除</button>
            </div>
        </div>
    `).join('');
}

// 更新模型选择下拉框
function updateModelSelect(models) {
    const select = document.getElementById('default-model-select');
    if (!select) return;

    select.innerHTML = models
        .filter(model => model.status === 1)
        .map(model => `<option value="${model.id}">${model.name}</option>`)
        .join('');
}

// 加载AI系统设置
function loadAISystemSettings() {
    return fetch('/xuanzheng-company/aiSystemSettings')
        .then(response => response.json())
        .then(data => {
            updateAISettingsUI(data);
        })
        .catch(error => {
            console.error('加载AI系统设置失败:', error);
        });
}

// 更新AI设置UI
function updateAISettingsUI(settings) {
    // 更新默认限制
    const limitInput = document.getElementById('default-daily-limit');
    if (limitInput && settings.defaultDailyLimit) {
        limitInput.value = settings.defaultDailyLimit;
    }

    // 更新AI启用状态
    const enabledSelect = document.getElementById('ai-enabled');
    if (enabledSelect && settings.aiEnabled !== undefined) {
        enabledSelect.value = settings.aiEnabled;
    }

    // 更新默认模型
    const modelSelect = document.getElementById('default-model-select');
    if (modelSelect && settings.defaultModelId) {
        modelSelect.value = settings.defaultModelId;
    }
}

// 更新默认每日限制
function updateDefaultLimit() {
    const input = document.getElementById('default-daily-limit');
    const value = input ? input.value : '';

    if (!value || isNaN(value) || value < 1) {
        showToast('错误', '请输入有效的限制数量', 'error');
        return;
    }

    fetch('/xuanzheng-company/updateAISetting', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            key: 'default_daily_limit',
            value: value
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', '默认限制已更新', 'success');
        } else {
            showToast('错误', '更新失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新失败:', error);
        showToast('错误', '更新失败', 'error');
    });
}

// 更新AI功能启用状态
function updateAIEnabled() {
    const select = document.getElementById('ai-enabled');
    const value = select ? select.value : '';

    fetch('/xuanzheng-company/updateAISetting', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            key: 'ai_enabled',
            value: value
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', 'AI功能状态已更新', 'success');
        } else {
            showToast('错误', '更新失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新失败:', error);
        showToast('错误', '更新失败', 'error');
    });
}

// 更新默认模型
function updateDefaultModel() {
    const select = document.getElementById('default-model-select');
    const value = select ? select.value : '';

    if (!value) {
        showToast('错误', '请选择默认模型', 'error');
        return;
    }

    fetch('/xuanzheng-company/updateAISetting', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            key: 'default_model_id',
            value: value
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', '默认模型已更新', 'success');
        } else {
            showToast('错误', '更新失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新失败:', error);
        showToast('错误', '更新失败', 'error');
    });
}

// 显示添加模型对话框
function showAddModelDialog() {
    const name = prompt('请输入模型名称:');
    if (!name || !name.trim()) return;

    const description = prompt('请输入模型描述 (可选):') || '';
    const apiUrl = prompt('请输入API地址:');
    if (!apiUrl || !apiUrl.trim()) return;

    const apiKey = prompt('请输入API密钥:');
    if (!apiKey || !apiKey.trim()) return;

    const maxTokensStr = prompt('请输入最大Token数 (默认2000):') || '2000';
    const maxTokens = parseInt(maxTokensStr);
    if (isNaN(maxTokens) || maxTokens <= 0) {
        showToast('错误', '最大Token数必须是正整数', 'error');
        return;
    }

    const temperatureStr = prompt('请输入温度参数 (0-1, 默认0.7):') || '0.7';
    const temperature = parseFloat(temperatureStr);
    if (isNaN(temperature) || temperature < 0 || temperature > 1) {
        showToast('错误', '温度参数必须在0-1之间', 'error');
        return;
    }

    // 添加模型
    addAIModel({
        name: name.trim(),
        description: description.trim(),
        apiUrl: apiUrl.trim(),
        apiKey: apiKey.trim(),
        maxTokens: maxTokens,
        temperature: temperature
    });
}

// 编辑AI模型
function editAIModel(modelId) {
    // 首先获取模型信息
    fetch('/xuanzheng-company/aiModels')
    .then(response => response.json())
    .then(models => {
        const model = models.find(m => m.id === modelId);
        if (!model) {
            showToast('错误', '找不到模型信息', 'error');
            return;
        }

        const name = prompt('请输入模型名称:', model.name);
        if (!name || !name.trim()) return;

        const description = prompt('请输入模型描述:', model.description || '') || '';
        const apiUrl = prompt('请输入API地址:', model.apiUrl);
        if (!apiUrl || !apiUrl.trim()) return;

        const apiKey = prompt('请输入API密钥 (留空保持不变):') || '***';

        const maxTokensStr = prompt('请输入最大Token数:', model.maxTokens.toString()) || model.maxTokens.toString();
        const maxTokens = parseInt(maxTokensStr);
        if (isNaN(maxTokens) || maxTokens <= 0) {
            showToast('错误', '最大Token数必须是正整数', 'error');
            return;
        }

        const temperatureStr = prompt('请输入温度参数 (0-1):', model.temperature.toString()) || model.temperature.toString();
        const temperature = parseFloat(temperatureStr);
        if (isNaN(temperature) || temperature < 0 || temperature > 1) {
            showToast('错误', '温度参数必须在0-1之间', 'error');
            return;
        }

        // 更新模型
        updateAIModel({
            id: modelId,
            name: name.trim(),
            description: description.trim(),
            apiUrl: apiUrl.trim(),
            apiKey: apiKey.trim(),
            maxTokens: maxTokens,
            temperature: temperature
        });
    })
    .catch(error => {
        console.error('获取模型信息失败:', error);
        showToast('错误', '获取模型信息失败', 'error');
    });
}

// 切换AI模型状态
function toggleAIModel(modelId, currentStatus) {
    const newStatus = currentStatus === 1 ? 0 : 1;
    const action = newStatus === 1 ? '启用' : '禁用';
    
    if (confirm(`确定要${action}此模型吗？`)) {
        fetch('/xuanzheng-company/aiModelManagement?action=toggle&modelId=' + encodeURIComponent(modelId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('成功', data.message, 'success');
                loadAIModels(); // 重新加载模型列表
            } else {
                showToast('错误', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('切换模型状态失败:', error);
            showToast('错误', '切换模型状态失败', 'error');
        });
    }
}

// 删除AI模型
function deleteAIModel(modelId) {
    if (confirm('确定要删除此模型吗？此操作不可恢复！')) {
        fetch('/xuanzheng-company/aiModelManagement?action=delete&modelId=' + encodeURIComponent(modelId), {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('成功', data.message, 'success');
                loadAIModels(); // 重新加载模型列表
            } else {
                showToast('错误', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除模型失败:', error);
            showToast('错误', '删除模型失败', 'error');
        });
    }
}

// 添加AI模型
function addAIModel(modelData) {
    fetch('/xuanzheng-company/aiModelManagement?action=add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(modelData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', data.message, 'success');
            loadAIModels(); // 重新加载模型列表
        } else {
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('添加模型失败:', error);
        showToast('错误', '添加模型失败', 'error');
    });
}

// 更新AI模型
function updateAIModel(modelData) {
    fetch('/xuanzheng-company/aiModelManagement?action=update', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(modelData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('成功', data.message, 'success');
            loadAIModels(); // 重新加载模型列表
        } else {
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('更新模型失败:', error);
        showToast('错误', '更新模型失败', 'error');
    });
}

// 搜索用户（用于AI限制设置，不使用，保留废案）
function searchUserForAI() {
    const keyword = prompt('请输入用户姓名或手机号:');
    if (!keyword || !keyword.trim()) return;

    fetch('/xuanzheng-company/aiUserSearch?keyword=' + encodeURIComponent(keyword.trim()))
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayUserSearchResults(data.users);
        } else {
            showToast('错误', data.message, 'error');
        }
    })
    .catch(error => {
        console.error('搜索用户失败:', error);
        showToast('错误', '搜索用户失败', 'error');
    });
}

// 显示用户搜索结果
function displayUserSearchResults(users) {
    if (!users || users.length === 0) {
        showToast('提示', '没有找到匹配的用户', 'info');
        return;
    }

    let resultHtml = '<div class="user-search-results">';
    resultHtml += '<h4>搜索结果:</h4>';
    resultHtml += '<ul>';
    
    users.forEach(user => {
        resultHtml += `<li>
            <span>${user.name} (${user.phone}) - 当前限制: ${user.dailyLimit || '使用默认'}</span>
            <button class="btn btn-sm btn-primary" onclick="setUserLimit('${user.id}', '${user.name}')">设置限制</button>
        </li>`;
    });
    
    resultHtml += '</ul></div>';
    
    // 显示结果（可以用模态框或直接在页面中显示）
    // 这里简单使用alert显示，实际应用中可以用更好的UI
    const resultsWindow = window.open('', 'searchResults', 'width=600,height=400,scrollbars=yes');
    resultsWindow.document.write(`
        <html>
            <head><title>用户搜索结果</title>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; }
                li { margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }
                .btn { background: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; }
                .btn:hover { background: #0056b3; }
            </style>
            </head>
            <body>${resultHtml}</body>
        </html>
    `);
}

// 设置用户AI使用限制
function setUserLimit(userId, userName) {
    const limitStr = prompt(`请输入用户"${userName}"的每日AI提问次数限制:`);
    if (!limitStr) return;
    
    const limit = parseInt(limitStr);
    if (isNaN(limit) || limit < 0) {
        showToast('错误', '限制次数必须是非负整数', 'error');
        return;
    }

    // TODO: 实现设置用户限制的接口
    showToast('提示', '设置用户限制功能需要后端接口支持', 'info');
}